package com.github.tangyi.consumer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;

@EnableDiscoveryClient
@RestController
@SpringBootApplication
@EnableFeignClients
public class ConsulConsumerApplication {

    @Autowired
    private HelloService helloService;

    @Value("${test}")
    private String test;

    public static void main(String[] args) {
        SpringApplication.run(ConsulConsumerApplication.class, args);
    }

    @GetMapping("hello")
    public String hello(String name) {
        return helloService.sayHello(name);
    }

    @GetMapping("testAdmin")
    @PreAuthorize("hasAuthority('ADMIN')")
    public String testAdmin() {
        return "testAdmin:" + test;
    }

    @GetMapping("testUser")
    @PreAuthorize("hasAuthority('USER')")
    public String testUser() {
        return "testUser:" + test;
    }

    @GetMapping("testAdminOrUser")
    @PreAuthorize("hasAuthority('ADMIN') or hasAuthority('USER')")
    public String testAdminOrUser() {
        return "testAdminOrUser:" + test;
    }

    @GetMapping(path = "/user/details", produces = "application/json" )
    public Principal userDetails(Principal principal) {
        return principal;
    }
}
